package com.ygswglxt.attendance.controller;

import com.ygswglxt.attendance.service.AttendanceService;
import com.ygswglxt.common.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/attendance/dashboard")
public class DashboardController {
    
    @Autowired
    private AttendanceService attendanceService;
    
    /**
     * 获取数据可视化仪表盘数据
     */
    @GetMapping("/data")
    public Result<Map<String, Object>> getDashboardData(
            @RequestParam(required = false) String month,
            HttpServletRequest request) {
        try {
            String role = request.getHeader("role");
            // HR和经理可以查看，员工只能查看自己的
            if (role == null || (!"HR".equals(role) && !"MANAGER".equals(role))) {
                return Result.error(403, "无权限访问");
            }
            
            // 如果没有指定月份，使用当前月份
            if (month == null || month.isEmpty()) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
                month = sdf.format(new Date());
            }
            
            Map<String, Object> result = new HashMap<>();
            
            // 1. 获取基础统计数据
            Result<Map<String, Object>> attendanceStatsResult = attendanceService.getAttendanceStatistics(month);
            Map<String, Object> attendanceStats = attendanceStatsResult.getData();
            
            Map<String, Object> statistics = new HashMap<>();
            if (attendanceStats != null && attendanceStats.containsKey("statistics")) {
                statistics = (Map<String, Object>) attendanceStats.get("statistics");
            }
            result.put("statistics", statistics);
            
            // 2. 考勤趋势数据（最近7天的打卡次数）
            List<Map<String, Object>> attendanceTrend = getAttendanceTrend(month);
            result.put("attendanceTrend", attendanceTrend);
            
            // 3. 异常类型分布
            List<Map<String, Object>> exceptionType = getExceptionTypeDistribution(month);
            result.put("exceptionType", exceptionType);
            
            // 4. 请假类型分布（需要调用leave服务，这里先返回空数据）
            List<Map<String, Object>> leaveType = getLeaveTypeDistribution();
            result.put("leaveType", leaveType);
            
            // 5. 出勤率统计
            List<Map<String, Object>> attendanceRate = getAttendanceRateDistribution(month);
            result.put("attendanceRate", attendanceRate);
            
            return Result.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取数据失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取考勤趋势数据（指定月份每天的打卡次数）
     */
    private List<Map<String, Object>> getAttendanceTrend(String month) {
        List<Map<String, Object>> trend = new ArrayList<>();
        
        try {
            // 查询数据库中该月份每天的打卡次数
            List<Map<String, Object>> dailyData = attendanceService.getDailyCheckInsByMonth(month);
            
            // 将查询结果转换为趋势数据格式
            for (Map<String, Object> dayData : dailyData) {
                Map<String, Object> trendItem = new HashMap<>();
                trendItem.put("date", dayData.get("date"));
                // checkIns 可能是 Long 或 Integer，统一转换为 Integer
                Object checkInsObj = dayData.get("checkIns");
                if (checkInsObj instanceof Number) {
                    trendItem.put("checkIns", ((Number) checkInsObj).intValue());
                } else {
                    trendItem.put("checkIns", 0);
                }
                trend.add(trendItem);
            }
        } catch (Exception e) {
            e.printStackTrace();
            // 如果查询失败，返回空列表
        }
        
        return trend;
    }
    
    /**
     * 获取异常类型分布
     */
    private List<Map<String, Object>> getExceptionTypeDistribution(String month) {
        List<Map<String, Object>> distribution = new ArrayList<>();
        
        try {
            // 查询迟到记录
            Result<List<com.ygswglxt.attendance.entity.AttendanceRecord>> lateResult = 
                attendanceService.getExceptionRecords(null, month, "LATE", null);
            int lateCount = lateResult.getData() != null ? lateResult.getData().size() : 0;
            
            // 查询早退记录
            Result<List<com.ygswglxt.attendance.entity.AttendanceRecord>> earlyLeaveResult = 
                attendanceService.getExceptionRecords(null, month, "EARLY_LEAVE", null);
            int earlyLeaveCount = earlyLeaveResult.getData() != null ? earlyLeaveResult.getData().size() : 0;
            
            // 查询缺勤记录
            Result<List<com.ygswglxt.attendance.entity.AttendanceRecord>> absentResult = 
                attendanceService.getExceptionRecords(null, month, "ABSENT", null);
            int absentCount = absentResult.getData() != null ? absentResult.getData().size() : 0;
            
            if (lateCount > 0) {
                Map<String, Object> item = new HashMap<>();
                item.put("name", "迟到");
                item.put("value", lateCount);
                distribution.add(item);
            }
            
            if (earlyLeaveCount > 0) {
                Map<String, Object> item = new HashMap<>();
                item.put("name", "早退");
                item.put("value", earlyLeaveCount);
                distribution.add(item);
            }
            
            if (absentCount > 0) {
                Map<String, Object> item = new HashMap<>();
                item.put("name", "缺勤");
                item.put("value", absentCount);
                distribution.add(item);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return distribution;
    }
    
    /**
     * 获取请假类型分布
     */
    private List<Map<String, Object>> getLeaveTypeDistribution() {
        List<Map<String, Object>> distribution = new ArrayList<>();
        
        // 这里应该调用leave服务获取数据，简化处理返回空数据
        // 实际实现时需要注入LeaveService或通过Feign调用leave服务
        
        return distribution;
    }
    
    /**
     * 获取出勤率分布
     */
    private List<Map<String, Object>> getAttendanceRateDistribution(String month) {
        List<Map<String, Object>> distribution = new ArrayList<>();
        
        try {
            Result<Map<String, Object>> statsResult = attendanceService.getAttendanceStatistics(month);
            Map<String, Object> stats = statsResult.getData();
            
            if (stats != null && stats.containsKey("details")) {
                List<Map<String, Object>> details = (List<Map<String, Object>>) stats.get("details");
                
                int rate90Plus = 0;
                int rate80To90 = 0;
                int rate70To80 = 0;
                int rateBelow70 = 0;
                
                for (Map<String, Object> detail : details) {
                    Object rateObj = detail.get("attendanceRate");
                    if (rateObj != null) {
                        int rate = ((Number) rateObj).intValue();
                        if (rate >= 90) {
                            rate90Plus++;
                        } else if (rate >= 80) {
                            rate80To90++;
                        } else if (rate >= 70) {
                            rate70To80++;
                        } else {
                            rateBelow70++;
                        }
                    }
                }
                
                if (rate90Plus > 0) {
                    Map<String, Object> item = new HashMap<>();
                    item.put("name", "90%以上");
                    item.put("value", rate90Plus);
                    distribution.add(item);
                }
                
                if (rate80To90 > 0) {
                    Map<String, Object> item = new HashMap<>();
                    item.put("name", "80-90%");
                    item.put("value", rate80To90);
                    distribution.add(item);
                }
                
                if (rate70To80 > 0) {
                    Map<String, Object> item = new HashMap<>();
                    item.put("name", "70-80%");
                    item.put("value", rate70To80);
                    distribution.add(item);
                }
                
                if (rateBelow70 > 0) {
                    Map<String, Object> item = new HashMap<>();
                    item.put("name", "70%以下");
                    item.put("value", rateBelow70);
                    distribution.add(item);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return distribution;
    }
}

